<template>
  <view :data-theme="g.theme">
    <BasicComponents></BasicComponents>
    <CustomNavbar title="工作日新增"></CustomNavbar>
    <view class="btn">
      <view class="row" @tap="openCalendar('search')">现有工作日</view>
      <view class="row" @tap="openCalendar('add')">新增工作日</view>
    </view>
    <!--  -->
    <up-calendar
      :show="calendarObj.visible"
      :default-date="displayDefaultDate"
      :month-num="5"
      :min-date="calendarObj.minDate"
      :max-date="calendarObj.maxDate"
      :color="g.basicColor.primary"
      @close="calendarObj.visible = false"
      @confirm="confirmCalendar"
      mode="multiple"
    ></up-calendar>
    <BottomButton></BottomButton>
  </view>
</template>
<script setup lang="ts">
import dayjs from "dayjs";

const g = useThemeStore();

onLoad(() => init());

let calendarObj = ref({
  visible: false,
  type: "search",
  // 已添加日期
  addDefaultDate: [],
  // 下个月所有的日期
  inNextMonth: [],
  minDate: dayjs().subtract(1, "month").format("YYYY-MM-DD"),
  maxDate: dayjs().add(4, "month").format("YYYY-MM-DD"),
  mode: "multiple"
});

const displayDefaultDate = computed(() => {
  const { type, addDefaultDate, inNextMonth } = calendarObj.value;
  return type === "search" ? addDefaultDate : inNextMonth;
});

const init = async () => {
  getDatesInNextMonth();
  const { minDate, maxDate } = calendarObj.value;
  const params = {
    start: minDate,
    end: maxDate
  };
  const data: any = await workdayFindWorkDayByScope(params);
  calendarObj.value.addDefaultDate = data.map(item => {
    return item.date;
  });
};

const confirmCalendar = dates => {
  const { type } = calendarObj.value;
  if (type === "add") {
    let d = [];
    for (let v of dates) {
      console.log(v, "v");
      d.push({
        date: v
      });
    }

    workdayAddWorkday({ workdayList: d });
    calendarObj.value.visible = false;
    useGlobalStore().setMessage();
    init();
  }
};

const openCalendar = (type: "search" | "add") => {
  calendarObj.value.type = type;
  calendarObj.value.visible = true;
};

/**
 * @description:获取下个月所有的日期
 * @return {*}
 */
const getDatesInNextMonth = () => {
  calendarObj.value.inNextMonth = [];
  const currentDate = dayjs();
  //下月第一天
  const nextMonthStart = currentDate.add(1, "month").startOf("month");
  // 下月最后一天
  const nextMonthEnd = currentDate.add(1, "month").endOf("month");

  // 循环获取下月每一天
  for (let i = nextMonthStart.date(); i <= nextMonthEnd.date(); i++) {
    const date = nextMonthStart.date(i).format("YYYY-MM-DD");
    calendarObj.value.inNextMonth.push(date);
  }
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
